package com.atguigu.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.dbutils.handlers.ColumnListHandler;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @ClassName: DruidUtils
 * @Description:
 * @Author: wty
 * @Date: 2022/12/5
 */

public class DruidUtils {
    private static DataSource dataSource;
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();


    static {
        Properties properties = new Properties();
        try {
            InputStream inputStream = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            properties.load(inputStream);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description: 获取链接
     * @Author: wty
     * @Date: 2022/12/4
     */
    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = threadLocal.get();
            if (null == connection) {
                connection = dataSource.getConnection();
                threadLocal.set(connection);
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return threadLocal.get();
    }

    public static void close(ResultSet resultSet, Statement statement, Connection connection) {
        //try {
        //
        //    if (null != resultSet) {
        //        resultSet.close();
        //    }
        //    if (null != statement) {
        //        statement.close();
        //    }
        //    if (null != connection) {
        //        connection.close();
        //    }
        //} catch (SQLException e) {
        //    throw new RuntimeException(e);
        //}
    }

    public static void closeConnection() throws SQLException {
        Connection connection = threadLocal.get();
        if (null == connection) {
            return;
        }
        if (!connection.isClosed()) {
            connection.close();
            threadLocal.set(null);
            // 或者remove也可以
            //threadLocal.remove();
        }
    }
}
